package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.CommentDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Comment;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS11010
 */
public class CS11010Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11010Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
			vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
			vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
	    	vaUrlAddress = request.getParameter("url_address");
	    	vaAgentBrowser = request.getParameter("agent_browser");
			String vaProcessType = request.getParameter("process_type");
			
			if(vaProcessType.equals("insert")){ 
				insert(request,response);	
			} else if(vaProcessType.equals("edit")){ 
				edit(request , response);
			}else if(vaProcessType.equals("delete")){
				delete(request,response);
			}else if(vaProcessType.equals("update")) {
				update(request,response);
			}else{
				getDataTable(request,response);
			}
    }
    
    public void update(HttpServletRequest request,
 			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		String vaCodeId = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		String vaOldCodeId = request.getParameter("oldCodeID");
		CommentDAO voCommentDAO = new CommentDAO(db);
		String vaCheckCodeId = voCommentDAO.findsCommentCodeBySiteAndCommentCode(vnSiteId, vaOldCodeId, vaCodeId);
		if(vaCheckCodeId == null){
			Comment poComment = new Comment();
			poComment.setVnSiteId(vnSiteId);
			poComment.setVaCommentCode(vaCodeId);
			poComment.setVaCommentDescription(vaDesp);
			poComment.setVnUpdateUserId(vnUserId);
			poComment.setVaUpdateDate(vaDate);
			poComment.setVaUpdateTime(vaTime);
			try {
				db.beginTransaction();
				voCommentDAO.updateCommentCode(vnSiteId, vaOldCodeId, poComment);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS110010", JDate.getDate(), JDate.getTime(),vnUserId, "CS110010Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			} finally{
				db.close();
			}
			response.getWriter().write("success");
			
		}else{
			db.close();
			response.getWriter().write("CodeID_Dupicate");
		}
    }
    public void insert(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		JDate jDate = new JDate();
		String date = jDate.getDate();
		String time = jDate.getTime();
		String vaCodeId = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		CommentDAO voCommentDAO = new CommentDAO(db);
		String vaCheckCodeId = voCommentDAO.findCommentCodeBySiteAndComment(vnSiteId, vaCodeId);
		if(vaCheckCodeId == null){
			Comment voComment = new Comment();
			voComment.setVnSiteId(vnSiteId);
			voComment.setVaCommentCode(vaCodeId);
			voComment.setVaCommentDescription(vaDesp);
			voComment.setVnInsertUserId(vnUserId);
			voComment.setVaInsertDate(date);
			voComment.setVaInsertTime(time);			
			try {
				db.beginTransaction();
				voCommentDAO.addCommentCode(voComment);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS110010", JDate.getDate(), JDate.getTime(),vnUserId, "CS110010Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally {
				db.close();
			}
			response.getWriter().write("success");
			
		}else{
			db.close();
			response.getWriter().write("CodeID_Dupicate");
		}
    }
    
    public void delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeId = request.getParameter("id");
		CommentDAO voCommentDAO = new CommentDAO(db);
		try {
			db.beginTransaction();
			voCommentDAO.deleteCommentCodeBySiteId(vnSiteId, vaCodeId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS110010", JDate.getDate(), JDate.getTime(),vnUserId, "CS110010Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally {
			db.close();
		}
		response.getWriter().write("delete_sucess");
    	
    }
    public void edit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaCodeId = request.getParameter("id");
		CommentDAO voCommentDAO = new CommentDAO(db);
		JSONObject voObject = new JSONObject();
		voObject.put("id",vaCodeId);
		voObject.put("desp", voCommentDAO.findDescriptionBySiteAndCommentCode(vnSiteId, vaCodeId));
		
		PrintWriter voOut = response.getWriter();
		
		db.close();
		voOut.print(voObject.toJSONString());
    	
    }
    public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		CommentDAO voCommentDAO = new CommentDAO(db);
		List<Map<String , Object>> voListFindAll;
		voListFindAll = voCommentDAO.findComment(vnSiteId);
	
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> mapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(mapItem.get("COMMENT_CODE")==null?"":mapItem.get("COMMENT_CODE").toString());
			voColumn.add(mapItem.get("COMMENT_DESCRIPTION")==null ?"" :mapItem.get("COMMENT_DESCRIPTION").toString());
			voRow.add(voColumn);
		}
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voListFindAll.size());
			voObject.put("aaData", voRow);
		
		db.close();
		 voOut.print(voObject.toJSONString());
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
